const RoleModel = require("../models/Role");
const assert = require("http-assert");
module.exports = () => {
    return async (req, res, next) => {
        const { user } = req.session;
        assert(user, 401, "请先登录");
        if (!req.session.permissionMenus) {
            console.log("写入菜单权限");
            let role = (await RoleModel.findOne({ name: user.role }).populate("menus")) || {};
            req.session.permissionMenus = role.menus || [];
        }
        if (!req.session.permissionInterfaces) {
            console.log("写入接口权限");
            let role = (await RoleModel.findOne({ name: user.role }).populate("menus")) || {};
            req.session.permissionInterfaces = role.interfaces || [];
        }
        const interfacesLink = req.session.permissionInterfaces.map(item => item.interface);
        assert(interfacesLink.includes(req.originalUrl.split("?")[0]), 403, "权限不足");
        next();
    };
};
